//
//  UIImage+Qrcode.m
//  paiKa
//
//  Created by lb on 16/4/7.
//  Copyright © 2016年 李波. All rights reserved.
//

#import "UIImage+Qrcode.h"

@implementation UIImage (Qrcode)


+ (UIImage *)getQrcodeImageWithString:(NSString *)string size:(CGSize)size{
    
    NSData *stringData = [string dataUsingEncoding:NSUTF8StringEncoding];
    // 创建filter
    CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 设置内容和纠错级别
    [qrFilter setValue:stringData forKey:@"inputMessage"];
    [qrFilter setValue:@"M" forKey:@"inputCorrectionLevel"];
    
    // return qrFilter.outputImage;
    
    UIImage *image = [self createNonInterpolatedUIImageFormCIImage:qrFilter.outputImage withSize:size];
    return image;
}

+ (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGSize)size {
    

    CGRect extent = CGRectIntegral(image.extent);
    
    CGFloat widthScale = size.width/CGRectGetWidth(extent);
    CGFloat heightScale = size.height/CGRectGetHeight(extent);
    // 创建bitmap;
    size_t width = size.width;
    size_t height = size.height;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, widthScale, heightScale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    // 保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

/*
 CGRect extent = CGRectIntegral(image.extent);
 CGFloat scale = size.width/CGRectGetWidth(extent);
 
 // 1.创建bitmap;
 size_t width = CGRectGetWidth(extent) * scale;
 size_t height = CGRectGetHeight(extent) * scale;
 CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
 CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
 CIContext *context = [CIContext contextWithOptions:nil];
 CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
 CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
 CGContextScaleCTM(bitmapRef, scale, scale);
 CGContextDrawImage(bitmapRef, extent, bitmapImage);
 
 // 2.保存bitmap到图片
 CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
 CGContextRelease(bitmapRef);
 CGImageRelease(bitmapImage);
 return [UIImage imageWithCGImage:scaledImage];
 */


@end
